package com.app.mingluxing.base;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.app.mingluxing.bean.EmoBean;
import com.app.mingluxing.mqtt.MQTTService;
import com.app.mingluxing.mqtt.MqttManager;
import com.app.mingluxing.net.OkHttpStack;
import com.app.mingluxing.utils.ParserBrowXml;
import com.baidu.mapapi.SDKInitializer;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.squareup.okhttp.OkHttpClient;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by Aaron on 2015/7/27.
 */
public class MyApplication extends Application {

    public static final String TAG = MyApplication.class.getSimpleName();
    //    private SharedPreferences sp;
    private Intent serviceIntent;
    public static MyApplication instance = null;

    public static MyApplication getInstance() {
        return instance;
    }


    private HashMap<String, String> emos;
    private List<EmoBean> emoBeanList;

//    public static String currentBabyName;

//    //绑定的孩子的集合
//    public List<BindChildList.Data> bindChildList;
//    //当前选中孩子的id
//    public String currentChildId;

    // 存放activity
    private List<Activity> activityList = new LinkedList<Activity>();
    /**
     * 我的定位坐标的点
     */
    public double myLatitude;
    public double myLongitude;

    //网络请求队列
    private RequestQueue mRequestQueue;

//    public File homeBgFile;

    public void onCreate() {
        super.onCreate();
        instance = this;

//		 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
//         .build();
//
//		// imageload 加载图片
//		ImageLoader.getInstance().init(config);
        ImageLoader.getInstance().init(getSimpleConfig());

        // 在Appliction里面设置我们的异常处理器为UncaughtExceptionHandler处理器
        CrashHandler handler = CrashHandler.getInstance();
        handler.init(getApplicationContext());

        // 百度地图在使用SDK各组件之前初始化context信息，传入ApplicationContext
        // 注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());

//        sp = getSharedPreferences(Constant.CONFIG, MODE_PRIVATE);

        //极光推送
//        JPushInterface.setDebugMode(true);//是否开启debug模式
        JPushInterface.init(this);
        //sharesdk短信验证
//        SMSSDK.initSDK(this, "660dffa7a1fa", "5dd350254d3516c273a79c41a9a1db45");

    }

    /**
     * 比较常用的配置方案
     *
     * @return
     */
    @Deprecated
    private ImageLoaderConfiguration getSimpleConfig() {

        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(true).cacheOnDisc(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .imageScaleType(ImageScaleType.IN_SAMPLE_INT).build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                getApplicationContext())
                .threadPoolSize(2)
                // 线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new WeakMemoryCache())
                .memoryCacheSize(20 * 1024 * 1024)
//				.discCache(ne)
                .discCacheSize(50 * 1024 * 1024).discCacheFileCount(100)
                // 缓存的文件数量
                .defaultDisplayImageOptions(defaultOptions)
                .imageDownloader(
                        new BaseImageDownloader(getApplicationContext(),
                                5 * 1000, 30 * 1000)) // connectTimeout
//								.writeDebugLogs()
                .build();// 开始构建

//        //设置缓存的路径
//        File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), "imageloader/Cache");
//
//        ImageLoaderConfiguration config = new ImageLoaderConfiguration
//            .Builder(getApplicationContext())
//            .memoryCacheExtraOptions(480, 800) //即保存的每个缓存文件的最大长宽
//            .threadPriority(Thread.NORM_PRIORITY - 2) //线程池中线程的个数
//            .denyCacheImageMultipleSizesInMemory() //禁止缓存多张图片
//            .memoryCache(new LRULimitedMemoryCache(10*1024*1024)) //缓存策略
//            .memoryCacheSize(20 * 1024 * 1024) //设置内存缓存的大小
//            .diskCacheFileNameGenerator(new Md5FileNameGenerator()) //缓存文件名的保存方式
//            .diskCacheSize(50 * 1024 * 1024) //磁盘缓存大小
//            .tasksProcessingOrder(QueueProcessingType.LIFO) //工作队列
//            .diskCacheFileCount(10) //缓存的文件数量
//            .diskCache(new UnlimitedDiskCache(cacheDir)) //自定义缓存路径
//            .writeDebugLogs() // Remove for release app
//            .build();
        return config;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new OkHttpStack(new OkHttpClient()));
//            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    //添加到请求队列
    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        //设置超时时间
        req.setRetryPolicy(new DefaultRetryPolicy(6 * 1000, 1, 1.0f));
        req.setShouldCache(false);
        getRequestQueue().add(req);
    }

    //从请求队列中删除
    public void cancelPendingRequests(Object tag) {
        getRequestQueue().cancelAll(tag);
    }

    // 添加Activity 到容器中
    public void addActivity(Activity activity) {
        activityList.add(activity);
    }

    /**
     * 获取表情的map集合 key是表情的匹配符如[满意], value是图片的名称
     *
     * @return
     */
    public Map<String, String> getEmoMap() {

        if (emos == null || emos.size() == 0) {

            try {
                emos = ParserBrowXml.getInfo(getResources().getAssets().open("brow.xml"));
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        return emos;

    }

    /**
     * 获取表情的list集合
     *
     * @return
     */
    public List<EmoBean> getEmoList() {

        if (emoBeanList == null || emoBeanList.size() == 0) {
            try {
                emoBeanList = ParserBrowXml.getListInfo(getResources().getAssets().open("brow.xml"));
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        return emoBeanList;
    }

    public void exit() {

        try {

            if (MqttManager.getInstance().getMqttClient() != null && MqttManager.getInstance().getMqttClient().isConnected())
                MqttManager.getInstance().getMqttClient().disconnect();
//            LogUtil.e("tag", "=======退出mqtt=====");

            //关闭聊天服务
            if (serviceIntent != null)
                stopService(serviceIntent);

//            LogUtil.e("tag", " activityList 的集合的个数 : " + activityList.size());

            for (Activity activity : activityList) {

                if (activity != null)
                    activity.finish();

            }
            activityList.clear();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            // 友盟统计
//            MobclickAgent.onKillProcess(this);
            System.exit(0);
        }

    }

    /**
     * 清除所有的activity
     */
    public void clearActivity() {

        try {
            for (Activity activity : activityList) {
//                LogUtil.e("tag", "activity===" + activity);
                if (activity != null)
                    activity.finish();
            }
            activityList.clear();
        } catch (Exception e) {
//            LogUtil.e("tag", "清理activity出错");
            e.printStackTrace();
        }

    }

//    /**
//     * 清除 除homeactivity的其他activity
//     */
//    public void clearActivityExceptHome() {
//
//        try {
//            for (Activity activity : activityList) {
//                if (activity != null) {
//                    if (activity instanceof HomeActivity)
//                        continue;
//                    activity.finish();
//                }
//            }
//            activityList.clear();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }


    //启动服务, 登录mqtt
    public void loginMqtt() {

        serviceIntent = new Intent(this, MQTTService.class);
        startService(serviceIntent);

    }

    public void exitMqtt() {

        if (serviceIntent != null)
            stopService(serviceIntent);
    }


}
